import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../../../common/utils/index.dart';
import 'index.dart';

class NetworkDiagnosticsPage extends GetView<NetworkDiagnosticsController> {
  const NetworkDiagnosticsPage({super.key});

  // 主视图构建方法
  Widget _buildView() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(height: 20),
          
          // 页面头部
          _buildHeader(),
          
          const SizedBox(height: 20),
          
          // 检测状态指示器
          _buildStatusIndicator(),
          
          const SizedBox(height: 30),
          
          // 操作按钮区域
          _buildActionButtons(),
          
          const SizedBox(height: 30),
          
          // 诊断结果区域
          if (controller.diagnosticResult.value != null)
            _buildDiagnosticResults(),
          
          if (controller.diagnosticReport.value.isNotEmpty)
            _buildDiagnosticReport(),
          
          const SizedBox(height: 20),
          
          // 诊断历史区域
          _buildHistorySection(),
          
          const SizedBox(height: 20),
          
          // 提示信息
          _buildTipsSection(),
        ],
      ),
    );
  }

  // 构建页面头部
  Widget _buildHeader() {
    return Column(
      children: [
        Container(
          width: 80,
          height: 80,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.blue.shade400, Colors.blue.shade600],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            shape: BoxShape.circle,
            boxShadow: [
              BoxShadow(
                color: Colors.blue.withOpacity(0.3),
                blurRadius: 15,
                offset: const Offset(0, 5),
              ),
            ],
          ),
          child: const Icon(
            Icons.network_check,
            color: Colors.white,
            size: 40,
          ),
        ),
        const SizedBox(height: 20),
        const Text(
          '网络诊断',
          style: TextStyle(
            fontSize: 28,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '检测和诊断网络连接问题',
          style: TextStyle(
            fontSize: 16,
            color: Colors.grey.shade600,
          ),
        ),
      ],
    );
  }

  // 构建检测状态指示器
  Widget _buildStatusIndicator() {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: controller.isRunningDiagnostics.value 
            ? Colors.blue.shade50 
            : controller.diagnosticResult.value != null
                ? controller.getStatusColor(controller.diagnosticResult.value!.overallStatus).withOpacity(0.1)
                : Colors.grey.shade50,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: controller.isRunningDiagnostics.value 
              ? Colors.blue.shade200
              : controller.diagnosticResult.value != null
                  ? controller.getStatusColor(controller.diagnosticResult.value!.overallStatus).withOpacity(0.3)
                  : Colors.grey.shade200,
          width: 2,
        ),
      ),
      child: Column(
        children: [
          // 状态图标和动画
          SizedBox(
            height: 60,
            child: controller.isRunningDiagnostics.value
                ? _buildLoadingAnimation()
                : controller.diagnosticResult.value != null
                    ? _buildResultIcon()
                    : _buildIdleIcon(),
          ),
          
          const SizedBox(height: 12),
          
          // 状态文本
          Text(
            controller.isRunningDiagnostics.value
                ? '正在检测网络状态...'
                : controller.diagnosticResult.value != null
                    ? '检测完成 - ${controller.getStatusText(controller.diagnosticResult.value!.overallStatus)}'
                    : '准备开始网络诊断',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: controller.isRunningDiagnostics.value 
                  ? Colors.blue.shade700
                  : controller.diagnosticResult.value != null
                      ? controller.getStatusColor(controller.diagnosticResult.value!.overallStatus)
                      : Colors.grey.shade600,
            ),
          ),
          
          // 进度指示器（仅在检测时显示）
          if (controller.isRunningDiagnostics.value) ...[
            const SizedBox(height: 12),
            LinearProgressIndicator(
              backgroundColor: Colors.blue.shade100,
              valueColor: AlwaysStoppedAnimation<Color>(Colors.blue.shade600),
            ),
          ],
        ],
      ),
    );
  }

  // 构建加载动画
  Widget _buildLoadingAnimation() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(
          width: 40,
          height: 40,
          child: CircularProgressIndicator(
            strokeWidth: 3,
            valueColor: AlwaysStoppedAnimation<Color>(Colors.blue.shade600),
          ),
        ),
        const SizedBox(width: 16),
        Icon(
          Icons.network_check,
          size: 32,
          color: Colors.blue.shade600,
        ),
      ],
    );
  }

  // 构建结果图标
  Widget _buildResultIcon() {
    final result = controller.diagnosticResult.value!;
    return Icon(
      controller.getStatusIcon(result.overallStatus),
      size: 40,
      color: controller.getStatusColor(result.overallStatus),
    );
  }

  // 构建空闲图标
  Widget _buildIdleIcon() {
    return Icon(
      Icons.network_check_outlined,
      size: 40,
      color: Colors.grey.shade400,
    );
  }

  // 构建操作按钮区域
  Widget _buildActionButtons() {
    return Column(
      children: [
        // 完整诊断按钮
        SizedBox(
          width: double.infinity,
          height: 56,
          child: ElevatedButton.icon(
            onPressed: controller.isRunningDiagnostics.value 
                ? null 
                : controller.runFullDiagnostics,
            icon: controller.isRunningDiagnostics.value
                ? SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  )
                : Icon(Icons.search, size: 24),
            label: Text(
              controller.isRunningDiagnostics.value ? '诊断中...' : '完整网络诊断',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
            ),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue.shade600,
              foregroundColor: Colors.white,
              elevation: 3,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16),
              ),
            ),
          ),
        ),
        
        const SizedBox(height: 16),
        
        // 快速检测和清除结果按钮
        Row(
          children: [
            // 快速检测按钮
            Expanded(
              child: SizedBox(
                height: 48,
                child: ElevatedButton.icon(
                  onPressed: controller.isRunningDiagnostics.value 
                      ? null 
                      : controller.quickNetworkCheck,
                  icon: const Icon(Icons.speed, size: 20),
                  label: const Text('快速检测'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.orange.shade600,
                    foregroundColor: Colors.white,
                    elevation: 2,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                ),
              ),
            ),
            
            const SizedBox(width: 8),
            
            // 重试按钮
            Expanded(
              child: SizedBox(
                height: 48,
                child: ElevatedButton.icon(
                  onPressed: (controller.diagnosticResult.value != null && 
                             !controller.isRunningDiagnostics.value &&
                             controller.retryCount.value < NetworkDiagnosticsController.maxRetryCount)
                      ? controller.retryDiagnostics
                      : null,
                  icon: const Icon(Icons.refresh, size: 20),
                  label: Text('重试(${controller.retryCount.value}/${NetworkDiagnosticsController.maxRetryCount})'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.purple.shade600,
                    foregroundColor: Colors.white,
                    elevation: 2,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                ),
              ),
            ),
            
            const SizedBox(width: 8),
            
            // 清除结果按钮
            Expanded(
              child: SizedBox(
                height: 48,
                child: ElevatedButton.icon(
                  onPressed: (controller.diagnosticResult.value != null || 
                             controller.diagnosticHistory.isNotEmpty)
                      ? controller.clearDiagnosticResult
                      : null,
                  icon: const Icon(Icons.clear, size: 20),
                  label: const Text('清除'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.grey.shade600,
                    foregroundColor: Colors.white,
                    elevation: 2,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  // 构建诊断结果区域
  Widget _buildDiagnosticResults() {
    final result = controller.diagnosticResult.value!;
    
    return Container(
      margin: EdgeInsets.only(bottom: 20),
      padding: EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: Offset(0, 2),
          ),
        ],
        border: Border.all(
          color: controller.getStatusColor(result.overallStatus).withOpacity(0.3),
          width: 2,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 总体状态
          Row(
            children: [
              Icon(
                controller.getStatusIcon(result.overallStatus),
                color: controller.getStatusColor(result.overallStatus),
                size: 32,
              ),
              SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '总体状态',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: Colors.black87,
                      ),
                    ),
                    Text(
                      controller.getStatusText(result.overallStatus),
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: controller.getStatusColor(result.overallStatus),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          
          SizedBox(height: 20),
          Divider(),
          SizedBox(height: 16),
          
          // 详细检查项目
          Text(
            '详细检查结果',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Colors.black87,
            ),
          ),
          
          SizedBox(height: 12),
          
          _buildDiagnosticItem('基础网络连接', result.basicConnectivity),
          _buildDiagnosticItem('DNS解析能力', result.dnsResolution),
          _buildDiagnosticItem('API服务器连通', result.apiServerConnectivity),
          _buildDiagnosticItem('SSL证书状态', result.sslCertificate),
          _buildDiagnosticItem('Dio服务状态', result.dioServiceStatus),
        ],
      ),
    );
  }

  // 构建单个诊断项目
  Widget _buildDiagnosticItem(String title, NetworkStatus status) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Icon(
            controller.getStatusIcon(status),
            color: controller.getStatusColor(status),
            size: 20,
          ),
          SizedBox(width: 12),
          Expanded(
            child: Text(
              title,
              style: TextStyle(
                fontSize: 16,
                color: Colors.black87,
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
              color: controller.getStatusColor(status).withOpacity(0.1),
              borderRadius: BorderRadius.circular(6),
            ),
            child: Text(
              controller.getStatusText(status),
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w500,
                color: controller.getStatusColor(status),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建诊断报告区域
  Widget _buildDiagnosticReport() {
    return Container(
      margin: EdgeInsets.only(bottom: 20),
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.description, color: Colors.blue.shade600, size: 20),
              SizedBox(width: 8),
              Text(
                '详细诊断报告',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              Spacer(),
              TextButton.icon(
                onPressed: controller.shareDiagnosticReport,
                icon: Icon(Icons.share, size: 16),
                label: Text('分享'),
                style: TextButton.styleFrom(
                  foregroundColor: Colors.blue.shade600,
                  textStyle: TextStyle(fontSize: 12),
                ),
              ),
            ],
          ),
          
          SizedBox(height: 12),
          
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.grey.shade200),
            ),
            child: Text(
              controller.diagnosticReport.value,
              style: TextStyle(
                fontSize: 12,
                fontFamily: 'monospace',
                color: Colors.black87,
                height: 1.4,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建诊断历史区域
  Widget _buildHistorySection() {
    if (controller.diagnosticHistory.isEmpty) {
      return const SizedBox.shrink();
    }
    
    return Container(
      margin: const EdgeInsets.only(bottom: 20),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.history, color: Colors.grey.shade600, size: 20),
              const SizedBox(width: 8),
              const Text(
                '诊断历史',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              const Spacer(),
              if (controller.diagnosticHistory.length > 3)
                TextButton(
                  onPressed: controller.clearDiagnosticResult,
                  child: const Text(
                    '清除',
                    style: TextStyle(fontSize: 12),
                  ),
                ),
            ],
          ),
          const SizedBox(height: 12),
          ...controller.diagnosticHistory.take(3).map((history) => Padding(
            padding: const EdgeInsets.only(bottom: 4),
            child: Text(
              history,
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey.shade700,
                fontFamily: 'monospace',
              ),
            ),
          )),
          if (controller.diagnosticHistory.length > 3)
            Padding(
              padding: const EdgeInsets.only(top: 4),
              child: Text(
                '... 还有 ${controller.diagnosticHistory.length - 3} 条记录',
                style: TextStyle(
                  fontSize: 10,
                  color: Colors.grey.shade500,
                  fontStyle: FontStyle.italic,
                ),
              ),
            ),
        ],
      ),
    );
  }

  // 构建提示区域
  Widget _buildTipsSection() {
    return Column(
      children: [
        HintTipWidget.info(
          text: '网络诊断可以帮助您快速发现和解决网络连接问题',
        ),
        
        const SizedBox(height: 16),
        
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.amber.shade50,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.amber.shade200),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.lightbulb_outline, color: Colors.amber.shade600, size: 20),
                  const SizedBox(width: 8),
                  Text(
                    '使用提示',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: Colors.amber.shade800,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                '• 完整诊断：检查所有网络相关项目\n'
                '• 快速检测：仅检查基础网络连接\n'
                '• 重试功能：最多可重试${NetworkDiagnosticsController.maxRetryCount}次\n'
                '• 如果出现网络问题，请按照建议操作处理',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.amber.shade800,
                  height: 1.4,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<NetworkDiagnosticsController>(
      init: NetworkDiagnosticsController(),
      id: "network_diagnostics",
      builder: (_) {
        return Scaffold(
          appBar: AppBar(
            leading: IconButton(
              icon: Icon(Icons.arrow_back_ios, color: Colors.black87, size: 20),
              onPressed: () => Get.back(),
            ),
            title: Text(
              controller.pageTitle,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),
            backgroundColor: Colors.white,
            elevation: 0,
            scrolledUnderElevation: 0,
            surfaceTintColor: Colors.transparent,
            foregroundColor: Colors.black87,
            systemOverlayStyle: const SystemUiOverlayStyle(
              statusBarColor: Colors.transparent,
              statusBarIconBrightness: Brightness.dark,
            ),
          ),
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }
}
